package com.dinadi.yidi.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.text.TextUtils;


import com.dinadi.yidi.ui.MyApplication;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {

	public static String deleteSpace(String str) {
		str = str.trim().replaceAll("\n", ""); // .replaceAll("\t", "")
		return str;
	}

	/*public static String getVcardString(VcardInfo info) {
		String str = "";
		if (info == null) {
			return str;
		}
		str = info.name;
		if (TextUtils.isEmpty(str)) {
			str = info.uid;
		}
		return str;
	}*/

	/**
	 * 把时间转为响铃次数
	 */
	public static final int timeToRingCount(int ringtime) {
		// return ringtime%2 == 0 ? (ringtime/2) : (ringtime/2 + 1);
		return ringtime == 0 ? ringtime + 1 : ringtime;
	}

	/** 语音长度展示转换 */
	public static String turnAudioTime(int audioTime) {
		int time = (int) (audioTime / 1000.0f) /* + 1 */;
		return time + "\"";
	}

	/**
	 * 判断是否是移动号码
	 */
	public static boolean isCMCCNumber(String num) {
		return num == null ? false
				: num.matches("^((86)|(086)|(0086)|(\\+86)){0,1}((13[4-9])|(15[0-2|7-9])|(18[7-8])|182|147)\\d{8}$");
	}

	/**
	 * 判断是否是手机号码
	 */
	public static boolean isPhoneNumber(String num) {
		/*不判断号段了，变化太快，以后还得升级app才行，有很大的滞后性
		String reg = "^((86)|(086)|(0086)|(\\+86)){0,1}((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$";
		return !TextUtils.isEmpty(num) ? num.matches(reg) : false;
		*/
		if(TextUtils.isEmpty(num)) return false;
		else{
			if(num.length()!=11) return false;
			else{
				if(num.substring(0,1).equals("1")) return true;//首位号是1
				return false;
			}
		}
	}

	/**
	 * 判断用户名是否合法
	 * @return
	 */
	public static boolean isUserName(String user){
		String reg = "^[0-9a-zA-Z一-龥_]{1,20}$";
		return !TextUtils.isEmpty(user) ? user.matches(reg) : false;
	}
	
	/**
	 * 去除字符串中的空格、回车、换行符、制表符
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * 号码格式标准化<br>
	 * "00"+国家码+"裸号"
	 * 
	 * @param number
	 * @return
	 */
	public static String formatNumber(String number) {
		String ccode = getCountryCode();
		if (StringUtil.isValidate(number)) {
			number.replace("-", "");
			if (number.startsWith("00")) {
				return "+" + number.substring(2);
			} else if (number.startsWith("0")) {
				return "+" + number.substring(1);
			} else if (number.startsWith("+")) {
				return number;
			} else if (number.startsWith(ccode)) {
				return "+" + number;
			} else {
				return "+" + ccode + number;
			}
		}
		return "";
	}

	/**
	 * 获取国家码
	 * 
	 * @return
	 */
	public static String getCountryCode() {
		String COUNTRY_CODE = null;
		if (COUNTRY_CODE == null || COUNTRY_CODE.length() < 1) {
			TelephonyManager tm = (TelephonyManager) MyApplication.getApp()
					.getSystemService(Context.TELEPHONY_SERVICE);
			String cc = tm.getSimCountryIso();
			// 这里只是强制换位中国的，模拟器是美国的。
			cc = "cn";
			if (cc.startsWith("+")) {
				COUNTRY_CODE = cc.substring(1);
			} else {
				if (cc.equalsIgnoreCase("fr")) {
					COUNTRY_CODE = "33";
				} else if (cc.equalsIgnoreCase("cn")) {
					COUNTRY_CODE = "86";
				} else if (cc.equalsIgnoreCase("es")) {
					COUNTRY_CODE = "34";
				} else if (cc.equalsIgnoreCase("fi")) {
					COUNTRY_CODE = "358";
				} else if (cc.equalsIgnoreCase("us")) {
					COUNTRY_CODE = "1";
				} else {
					COUNTRY_CODE = "86";
				}
			}
		}
		return COUNTRY_CODE;
	}

	/**
	 * 判断list是否有效
	 */
	public static <T> boolean isListValidate(List<T> list) {
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}

	public static <K, V> boolean isMapValidate(Map<K, V> map) {
		if (map != null && !map.isEmpty()) {
			return true;
		}
		return false;
	}

	/**
	 * 判断字符串是否有效
	 * 
	 * @deprecated
	 */
	public static boolean isValidate(String str) {
		if (str != null && str.length() > 0) {
			return true;
		}
		return false;
	}
	/**
	 * 去掉0
	 * */
	 public static String subZeroAndDot(String s){
	    	if(s.indexOf(".") > 0){
	    	s = s.replaceAll("0+?$", "");//去掉多余的0
	    	s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
	    	}
	    	return s;
	    	}
	/**
	 * 判断首字母是否是英文字母
	 */
	@SuppressLint("DefaultLocale")
	public static String getAlpha(String str) {
		if (isValidate(str)) {
			char c = str.trim().substring(0, 1).charAt(0);
			// 正则表达式，判断首字母是否是英文字母
			Pattern pattern = Pattern.compile("^[A-Za-z]+$");
			if (pattern.matcher(c + "").matches()) {
				return (c + "").toUpperCase();
			}
		}
		return "#";
	}

	public static boolean equals(CharSequence a, CharSequence b) {
		if (a == b)
			return true;
		int length;
		if (a != null && b != null && (length = a.length()) == b.length()) {
			if (a instanceof String && b instanceof String) {
				return a.equals(b);
			} else {
				for (int i = 0; i < length; i++) {
					if (a.charAt(i) != b.charAt(i))
						return false;
				}
				return true;
			}
		}
		return false;
	}

	public static String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	public static String subStringBySplit(String src, String mark, int max) {
		String[] strs = src.split(mark);
		StringBuilder sb = new StringBuilder();
		int i = 0;
		while (true) {
			sb.append(strs[i]);
			i++;
			if (sb.length() < max && i < strs.length) {
				sb.append("、");
				continue;
			}
			break;
		}
		return sb.toString();
	}

	/**
	 * 获取联系人显示名称
	 * 
	 * @param localName
	 * @param nickName
	 * @param phoneNumber
	 * @return
	 */
	public static String getDisplayName(String localName, String nickName,
										String phoneNumber) {
		return TextUtils.isEmpty(localName) ? (TextUtils.isEmpty(nickName) ? phoneNumber
				: nickName)
				: localName;
	}

	public static String getFormatDisplayName(String localName,
											  String nickName, String phoneNumber) {
		return TextUtils.isEmpty(localName) ? (TextUtils.isEmpty(nickName) ? formatPhone2Short(phoneNumber)
				: nickName)
				: localName;
	}

	/*public static String getNotifyContentByContasts(
			ArrayList<STContact> groupMember) {
		int i = 0, size = groupMember.size();
		if (size <= 0) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		while (true) {
			STContact contact = groupMember.get(i);
			sb.append(getDisplayName(contact.localname, contact.nickname,
					contact.phoneNum));
			i++;
			if (i < size) {
				sb.append("、");
				continue;
			}
			break;
		}
		return sb.toString();
	}

	public static String getNotifyContentByConferees(List<STConferee> member) {
		int size = member.size();

		StringBuilder sb = new StringBuilder();
		for (int j = 0; j < size; j++) {
			sb.append(member.get(j).getContact().getDispalyName());
			if (j == (size - 1)) {
				break;
			}
			sb.append("、");
		}
		return sb.toString();
	}

	public static String getNotifyContentByVcard(List<VcardInfo> groupMember) {
		int i = 0, size = groupMember.size();
		if (size <= 0) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		while (true) {
			VcardInfo vcardInfo = groupMember.get(i);
			sb.append(getDisplayName(null, vcardInfo.name, vcardInfo.uid));
			i++;
			if (i < size) {
				sb.append("、");
				continue;
			}
			break;
		}
		return sb.toString();
	}*/

	public static String getString(Context context, int resId) {
		return context.getString(resId);
	}

	public static String formatPhone2Short(String phoneNum) {

		Pattern pattern = Pattern.compile("\\+\\d\\d");
		Matcher matcher = pattern.matcher(phoneNum);
		StringBuffer strBuffer = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(strBuffer, "");
		}
		String num = matcher.appendTail(strBuffer).toString();
		if (num.length() < 7) {
			return num;
		}
		StringBuffer reuslt = new StringBuffer(20);
		reuslt.append(num.substring(0, 3));
		reuslt.append("..");
		reuslt.append(num.substring(num.length() - 3, num.length()));
		return reuslt.toString();
	}

	public static String getPhone(String phoneNum) {
		Pattern pattern = Pattern.compile("\\+\\d\\d");
		Matcher matcher = pattern.matcher(phoneNum);
		StringBuffer strBuffer = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(strBuffer, "");
		}
		return matcher.appendTail(strBuffer).toString();
	}
	
	private static String FETION_SMS_NUMBER_PREFIXS = "12520";
	private static String MOBILE_NUMBER_PREFIXS_86 = "+86";
	private static String[] MOBILE_NUMBER_PREFIXS = {"+86", FETION_SMS_NUMBER_PREFIXS, "12593", "17951"};
	/**
	 * 清除号码前缀："+86", "12520", "12593", "17951"，具体请看 {@link #MOBILE_NUMBER_PREFIXS}；
	 * @param mobileNumber
	 * @return
	 */
	public static String clearMoblieNumberPrefix(String mobileNumber) {
		if (!TextUtils.isEmpty(mobileNumber)) {
			StringBuffer numberStr = new StringBuffer(mobileNumber);
			for (int i = 0; i < MOBILE_NUMBER_PREFIXS.length; i++) {
				if (mobileNumber.startsWith(MOBILE_NUMBER_PREFIXS[i])) {
					numberStr.delete(0, MOBILE_NUMBER_PREFIXS[i].length());
					break;
				}
			}
			if (numberStr.length() > 0) {
				int len = numberStr.length()-1 ;
				for (int i = 0; i < len; i++) {
					if (!Character.isDigit(numberStr.charAt(i))) {
						numberStr.deleteCharAt(i);
						len = numberStr.length()-1;
					}
				}
				return numberStr.toString();
			}
		}
		return null;
	}

	public static String[] getDays(String year, String month)
	{
		String[] days;
		int totalDay = 0;
		switch (Integer.parseInt(month)) {
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				totalDay = 31;
				break;
			case 6:
			case 4:
			case 9:
			case 11:
				totalDay = 30;
				break;
			case 2:
				if(isRunnian(year)){
					totalDay = 29;
				}
				else
				{
					totalDay = 28;
				}
				break;
			default:
				break;
		}
		days = new String[totalDay];
		for(int i=1; i<=totalDay; i++)
		{
			if(i<10)
				days[i-1] = "0"+i;
			else
				days[i-1] = i+"";
		}
		return days;
	}
	private static boolean isRunnian(String syear)
	{
		try{
			if(Integer.parseInt(syear)%4 ==0 && Integer.parseInt(syear)% 100 !=0|| Integer.parseInt(syear)%400 ==0 )
			{
				return true;
			}
			else
				return false;
		}catch(Exception e){}
		return false;

	}
}
